DECLARE @xml XML

SET @xml = 
(
    SELECT
        DocumentId
    ,   Title      = CAST('<![CDATA[' + ISNULL(Title,'') + ']]>' AS xml)
    FROM
        [Document] AS Template
    WHERE
        DocumentId IN
        (
            SELECT
                SegmentDocument.DocumentId
            FROM
                SegmentDocument
            WHERE
				SegmentDocument.SegmentId = dbo.fGetSegmentId('templates', DEFAULT)
			OR
                dbo.fSegmentIsChildOf(SegmentDocument.SegmentId, 'templates') = 1
        )
    OR
        DocumentId IN
        (
            SELECT
                Document.DocumentId
            FROM
                Document
            WHERE
				Document.SegmentId = dbo.fGetSegmentId('templates', DEFAULT)
			OR
                dbo.fSegmentIsChildOf(Document.SegmentId, 'templates') = 1
        )
    FOR XML AUTO, ELEMENTS, ROOT('Templates')
)

SELECT @xml